package main

import (
	"database/sql"
	"log"

	_ "github.com/lib/pq"
)

type Album struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:"artist"`
	Price  float64 `json:"price"`
}

type MemoryStorage struct {
	albums []Album
}

var albums = []Album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

type MySQLStorage struct {
	db *sql.DB
}

func (p *MySQLStorage) CreateShema() error {
	_, err := p.db.Exec(`
        CREATE TABLE IF NOT EXISTS albums (
            id SERIAL PRIMARY KEY,
            title TEXT,
            artist TEXT,
            price FLOAT
        )
    `)
	return err
}

func NewMySQLStorage() MySQLStorage {
	//[user[:password]@][net[(addr)]]/dbname[?param1=value1&...&paramN=valueN]

	connStr := "user=user password=pass dbname=/db sslmode=disable" // connect to a MySQL server running on a different host //connStr := "user=user password=pass dbname=tcp(127.0.0.1:3306)/db sslmode=disable"
	db, err := sql.Open("mysql", connStr)
	if err != nil {
		log.Fatal(err)
	}
	storage := MySQLStorage{db: db}
	err = storage.CreateShema()
	if err != nil {
		log.Fatal(err)
	}
	return storage
}

func (m *MySQLStorage) Create(album Album) error {
	_, err := m.db.Exec("INSERT INTO albums (title, artist, price) VALUES ($1, $2, $3)", album.Title, album.Artist, album.Price)
	return err
}

func (m *MySQLStorage) Read() ([]Album, error) {
	rows, err := m.db.Query("SELECT id, title, artist, price FROM albums")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var albums []Album
	for rows.Next() {
		var album Album
		err := rows.Scan(&album.ID, &album.Title, &album.Artist, &album.Price)
		if err != nil {
			return nil, err
		}
		albums = append(albums, album)
	}
	return albums, nil
}

func (m *MySQLStorage) Update(id string, a Album) error {

	m.db.QueryRow("UPDATE albums SET title = $1, artist = $2, price = $3 WHERE id = $4 RETURNING id, title, artist, price", a.Title, a.Artist, a.Price, id)
	return nil
}

func (m *MySQLStorage) Delete(id string) error {
	_, err := m.db.Exec("DELETE FROM albums WHERE id = $1", id)
	return err
}
